//
//  GlobalTempModuVC.swift
//  ZYA
//
//  Created by 邱仙凯 on 2023/7/3.
//  Copyright © 2023 zwb. All rights reserved.
//  配置菜单拼接养殖报表

import UIKit
import JJCollectionViewRoundFlowLayout_Swift
import ObjectMapper
import Kingfisher

class GlobalTempModuVC: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
    var refreshDfMenuClosure:(()->())?
    var dataArray = [MeSuperModel]()
    fileprivate var reportArray = [DyncReportModel]()
    lazy var collectionView:UICollectionView = {
        // 1.创建layout
        let sectionW = self.view.ks_width - 24
        let layout = JJCollectionViewRoundFlowLayout_Swift()
        layout.itemSize = CGSize(width: sectionW/4 - 0.5, height: sectionW/4 - 10)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 18, left: 12, bottom: 16, right: 12)
        
        // 2.创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .white
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.register(FunctionCenterCell.self, forCellWithReuseIdentifier: FunctionCenterCell.identifier)
        collectionView.register(FunctionCenterHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FunctionCenterHeader.identifier)
       
        return collectionView
    }()
    var limitIDS:[String]?// 权限ids数组，处理菜单过滤
    var moduleId = ""
    var ps_staff_id = ""
    init(moduleId:String,limitIDS:[String]? = nil,ps_staff_id:String) {
        self.moduleId = moduleId
        self.limitIDS = limitIDS
        self.ps_staff_id = ps_staff_id
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
   
       
        self.view.backgroundColor = .white
     
        
        collectionView.dataSource = self
        collectionView.delegate = self
        self.view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.top.left.right.bottom.equalTo(self.view)
        }
         self.setMenu()
       
    }
    
   
    func setMenu() {
        
//        let limitIDS = LimitsMenus.compactMap{ $0.menuId }
        getTempMenu(id: moduleId) { arr in
            self.dataArray = arr
             if DeveloperTool.shared.GetAllowAllLimit() {
                
            } else {
                if self.limitIDS.isSome {
                    for i in 0..<self.dataArray.count {
                        self.dataArray[i].tempArr = self.dataArray[i].tempArr.filter{ self.limitIDS!.contains($0.res_id.unwrap) || $0.res_id.unwrap == "" || $0.res_id.unwrap == "0" }
                    }
                }
                
            }
            // 过滤掉无权限的菜单目录
            self.dataArray = self.dataArray.filter{$0.tempArr.count>0}
            
            // 隐藏之前把菜单缓存了
            for item in self.dataArray {
                cachedDynamicArray.append((item.directory_nm.unwrap,item.tempArr))
            }
          
            
                 //  隐藏菜单的隐藏 引用菜单的组装 和模块id的写入
            for i in 0..<self.dataArray.count {
                self.dataArray[i].tempArr = configReferMenu4SecondLevel(self.dataArray[i].tempArr,module_id: self.moduleId)
                }
        
            
            getDyncReport(bigId: "100400") { arr in
                
                self.reportArray = arr
                
                // 过滤掉无权限的菜单目录
                self.reportArray = self.reportArray.filter{$0.reportList.count>0}
                
                
                
                self.collectionView.reloadData()
                 
            }
             
        }
      
     
 
    }
    
    
}


// MARK: - 代理和数据源
extension GlobalTempModuVC {
    
    
    func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
        
        let header = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FunctionCenterHeader.identifier, for: indexPath) as! FunctionCenterHeader
        if indexPath.section < self.dataArray.count {
            header.titleLabel.text = self.dataArray[indexPath.section].directory_nm
        } else {
            header.titleLabel.text = self.reportArray[indexPath.section - self.dataArray.count].item_nm
        }
        return header
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        
        return CGSize(width: KSGlobal.screenW, height: 40)
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return self.tempNumberofSection()
    }
    func tempNumberofSection() -> Int {
        return self.dataArray.count + self.reportArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return tempNumberOfItemsInSection(section: section)
    }
    func tempNumberOfItemsInSection(section:Int) -> Int {
        if section < self.dataArray.count {
            return self.dataArray[section].tempArr.count
        } else {
            return self.reportArray[section - self.dataArray.count].reportList.count
            
        }
    }
    
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        
        return tempcellForItemAt(collectionView, cellForItemAt: indexPath)
    }
    func tempcellForItemAt(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: FunctionCenterCell.identifier, for: indexPath as IndexPath) as! FunctionCenterCell
        if indexPath.section < self.dataArray.count {
            let one = self.dataArray[indexPath.section].tempArr[indexPath.row]
            cell.title.text = one.menu_nm
            
            if  let imageUrl = URL(string: configURLOK(latter: one.pic_url.unwrap)) {
                let resource = KF.ImageResource(downloadURL: imageUrl)
                cell.img.kf.setImage(with: resource, placeholder: UIImage(named:"1_ld"))
            } else {
                cell.img.image = UIImage(named:"new_img\(indexPath.row%5 + 1)")
            }
        } else {
            cell.title.text = self.reportArray[indexPath.section - self.dataArray.count].reportList[indexPath.row].report_name
            
            if let img = UIImage(named: self.reportArray[indexPath.section - self.dataArray.count].reportList[indexPath.row].report_name.unwrap) {
                cell.img.image = img
            } else {
                cell.img.image = UIImage(named:"new_img\(indexPath.row%5 + 1)")
            }
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        tempdidSelectItemAt(collectionView, didSelectItemAt: indexPath)
    }
    func tempdidSelectItemAt(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.section < self.dataArray.count {
            var one = self.dataArray[indexPath.section].tempArr[indexPath.row]
            one.module_id = moduleId
            
            go2TempUtil(pvc: self, rtemp: one)
           
        } else {
            let repOne = self.reportArray[indexPath.section - self.dataArray.count].reportList[indexPath.row]
            // 有下一级，弹出选择
            if let smList = repOne.smallList {
                var allArr = [nameAndModel<ReportList>]()
                for i in 0..<smList.count {
                    let one_x = nameAndModel(shows: [smList[i].report_name.unwrap], model: smList[i])
                    allArr.append(one_x)
                }
                let cle:(nameAndModel<ReportList>)->() = { one in
                    go2ChartForWeb_10(url: USERINFO.reportUrl.unwrap + USERINFO.picPath.unwrap,path: one.model.report_url.unwrap, title: one.model.report_name.unwrap, parameters: ["ps_zc_id":USERINFO.zOrgId.unwrap, "ps_staff_id":self.ps_staff_id], currentVC: self)
                    
                }
                
                let vc = KSSingleSelectUtil.initWithNav(title: repOne.report_name.unwrap, allArr: allArr, backClosure: cle)
                self.present_FullScreen(to: vc)
                
            } else {
                go2ChartForWeb_10(url: USERINFO.reportUrl.unwrap + USERINFO.picPath.unwrap,path: repOne.report_url.unwrap, title: repOne.report_name.unwrap, parameters: ["ps_zc_id":USERINFO.zOrgId.unwrap, "ps_staff_id":self.ps_staff_id], currentVC: self)
            }
        }
    }
    
    
}
extension GlobalTempModuVC : JJCollectionViewDelegateRoundFlowLayout_Swift{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 12, left: 12, bottom: 12, right: 12)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        let model = JJCollectionViewRoundConfigModel_Swift.init()
        model.cornerRadius = 8
        model.backgroundColor = UIColor(kshex:"#f9f9f9")
        
        
        return model;
        
    }
}

func getDyncReport(newFlag:Bool = false,bigId:String,result:@escaping (([DyncReportModel])->())) {
    KSNetwork.shared.doRequest(API.temp(.getReportInfo(big_menu_id: bigId))) { (data:BaseResult<DyncReportModel>) in
        if data.flag == TRUE {
            if let infos = data.infos {
                var reportArray = infos
                
                for i in 0..<reportArray.count {
                    let reportList = reportArray[i].reportList
                    var tempList = [ReportList]()
                    for rep in reportList { // 循环报表大类
                        if let index = tempList.getIndexFor({ (one) -> Bool in
                            one.report_name == rep.report_name
                        }) { // 如果存在相同的报表
                            if tempList[index].smallList.isSome { // 已经有下一级数组了
                                
                                var repOne = ReportList(JSON:["":""])!
                                repOne.report_name = "\(rep.report_name.unwrap)-\(rep.button_nm.unwrap)"
                                repOne.report_url = rep.report_url
                                tempList[index].smallList!.append(repOne)
                            } else { // 还没有下一级数组
                                
                                var smList = [ReportList]()
                                var repOne = ReportList(JSON:["":""])!
                                repOne.report_name = "\(tempList[index].report_name.unwrap)-\(tempList[index].button_nm.unwrap)"
                                repOne.report_url = tempList[index].report_url
                                smList.append(repOne)
                                var repTwo = ReportList(JSON:["":""])!
                                repTwo.report_name = "\(rep.report_name.unwrap)-\(rep.button_nm.unwrap)"
                                repTwo.report_url = rep.report_url
                                smList.append(repTwo)
                                tempList[index].smallList = smList
                            }
                        }  else { // 没有存在就直接添加
                            tempList.append(rep)
                        }
                    }
                    
                    reportArray[i].reportList = tempList
 
                }
                 result(reportArray)
            }
        } else {
            result([])
        }
        
    }
}

struct DyncReportModel: Mappable {
    
    var idkey: String?
    var idkey2: Int?
    var z_name:String?
    var idkeyString: String?
    var vouId: String?
    var flag: String?
    var info: String?
    var message: String?
    var fid:String?
    var accessToken:String?
    var oa_dept_id:String?
    var z_month:String?
    var z_money:Double?
    var z_number:Int?
    var c_name:String?
    var sumMoney:Double?
    var sumApply:Double?
    
    var batchNum:Int?
    var sumNumber:Int?
    var zWeight:Double?
    var sumWeight:Double?
    var avgWeight:Double?
    var img_url:String?
    var reportList = [ReportList]()
     var item_nm:String?
    var token:String?
     var z_opt_dt:String?
    var z_scheme_nm:String?
    var z_weeks:String?
    var z_zzda_id:String?
     var zRecordNum:String?
    var z_pic_url:String?
    var z_project:String?
    var z_date:String?
    var url:String?
    var if_solo_nm:String?
    var if_solo:String?
     var z_product_id:String?
    var z_product_nm:String?
    
    var z_color:String?
    var z_stage:String?
    var z_type:String?
    var count:String?
    
    var name:String?
    var value:[String]?
    init?(map: Map) {
        
    }
    // Mappable
    mutating func mapping(map: Map) {
        item_nm <- map[DynsReportKeys.item_nm]
         name <- map["name"]
        value <- map["value"]
       

        z_color <- map["z_color"]
        z_stage <- map["z_stage"]
        z_type <- map["z_type"]
        sumApply <- map["sum_apply"]
        
        
        
        url <- map["url"]
        vouId <- map["vou_id"]
        count <- (map["count"],StringTransform())
        z_name <- map["z_name"]

        c_name <- map["c_name"]
        idkey <- (map["id_key"],StringTransform())
        if_solo_nm <- map["if_solo_nm"]
        if_solo <- (map["if_solo"],StringTransform())
        z_product_nm <- map["z_product_nm"]
        z_product_id <- (map["z_product_id"],StringTransform())
        idkey2 <- map["idkey"]
        idkeyString <- map["idkey"]
 
        flag <- map["flag"]
        info <- map["info"]
        message <- map["message"]
        z_pic_url <- map["z_pic_url"]
        fid <- map["fid"]
        accessToken <- map["accessToken"]
        z_month <- map["z_month"]
        z_money <- map["z_money"]
        z_number <- map["z_number"]
        sumMoney <- map["sum_money"]
        batchNum <- map["batch_num"]
        sumNumber <- map["sum_number"]
        sumWeight <- map["sum_weight"]
        zWeight <- map["z_weight"]
        avgWeight <- map["avg_weight"]
        img_url <- map["img_url"]
        reportList <- map["reportList"]
         token <- map["token"]
         z_opt_dt <- map["z_opt_dt"]
        z_scheme_nm <- map["z_scheme_nm"]
        oa_dept_id <- (map["oa_dept_id"],StringTransform())
        z_zzda_id <- (map["z_zzda_id"],StringTransform())
         zRecordNum <- map["z_record_num"]
        z_project <- map["z_project"]
        z_date <- map["z_date"]
      
        
    }
    
}
struct ReportList: Mappable {
    
    var report_name:String?
    var s_menu_img:String?
    var report_url:String?
    var button_nm:String?
    var z_pic_url:String?
    var smallList:[ReportList]?
    init?(map: Map) {
        
    }
    // Mappable
    mutating func mapping(map: Map) {
        s_menu_img <-  map["s_menu_img"]
        report_name <-  map["report_name"]
        report_url <-  map["report_url"]
        button_nm <-  map["button_nm"]
        z_pic_url <-  map["z_pic_url"]

        // 兼容新友安云取值逻辑
        if s_menu_img == nil {
            s_menu_img <- map["c_menu_img"]
        }
        if report_name == nil {
            report_name <- map["c_report_name"]
        }
        if report_url == nil {
            report_url <-  map["c_report_url"]
        }
        if button_nm == nil {
            button_nm <-  map["c_button_nm"]
        }
        if z_pic_url == nil {
            z_pic_url <-  map["c_pic_url"]
        }
    }
}
